<?php
class CustomControllerBase extends VTController {
	protected $pageName = '';
	
	/**	 * UserSessionVisitDataService object	 *	 * @var UserSessionVisitDataService object	 */
	public $userSessionVisitDataService = null;
	
	/**	 * UserPageDataService object	 *	 * @var UserPageDataService object	 */
	protected $userPageDataService = null;
	
	/*	 * Owner User of this Page	 */
	public $ownerId = null;
	
	/*	 * Owner User of this Page	 */
	public $ownerName = null;
	
	public $ownerFullName = null;
	
	/**	 * Current Template Folder	 * @var string	 */
	public $templateName = "";
	
	/**	 *	 * Authentication Object	 * @var Authentication Object	 */
	protected $authentication = null;
	
	/**	 *	 * Current Package Option of User	 * @var PackageOptionsEntity Object	 */
	protected $currentPackageOption = NULL;
	
	/**	 *	 * SettingsDataService Object	 * @var SettingsDataService Object	 */
	protected $settingsDataService = null;
	
	/**	 * UserBlogDataService object	 *	 * @var UserBlogDataService object	 */
	protected $userBlogDataService = null;
	
	/**	 * UserPhotoDataService object	 *	 * @var UserPhotoDataService object	 */
	protected $userPhotoDataService = null;
	
	/**	 * UserNewsDataService object	 *	 * @var UserNewsDataService object	 */
	protected $userNewsDataService = null;
	
	/**	 * UserProductDataService object	 *	 * @var UserProductDataService object	 */
	protected $userProductDataService = null;
	
	/**	 * Check if DEMO mode	 * @var boolean	 */
	protected $isDemoMode = false;
	
	protected $paypal_enable = false;
	protected $checkout_enable = false;
	protected $googlecheckout_enable = false;
	protected $worldpay_enable = false;
	protected $eway_enable = false;
	protected $currencyCode = "GBP";
	protected $currencySymbol = "";
	protected $isError = false;
	protected $error = "";
	
	/**	 * Check if it's Mobile Mode	 * @var boolean	 */
	protected $isMobileMode = false;
	
	/**	 * Constructor of Controller Base	 */
	public function __construct() {
		parent::__construct ();
		$this->setPageName ( $this->pageName );
		
		// Init Authentication class		$this->authentication = new Authentication ();
		$this->settingsDataService = new SettingsDataService ();
		$this->smarty->assign ( 'this', $this );
		$config = Zend_Registry::get ( 'config' );
		
		//Detect which is owner of this page		$username = $this->getQuery ( "u", "" );
		$userId = 0;
		if (empty ( $username )) {
			$domain = $_SERVER ["SERVER_NAME"];
			$name = SETTINGS_USER_DOMAIN;
			
			$pos = strpos ( $domain, "www." );
			if ($pos === false) {
				// Just do nothings				$domain = "www." . $domain;
			}
			
			// Detect via Domain name			// Check if there's user setting with domain			$settingItem = $this->settingsDataService->getUserFromDomain ( $name, $domain );
			if ($settingItem) {
				$userId = $settingItem->ownerId;
				
				// This case is used to test on localhost				if ("localhost" == ASS_DEFAUL_DOMAIN_1) {
					$newApplicationUrl = "http://" . $domain . ":8080/slappit1/Sources";
				} else {
					// Update APPLICATION_URL config					$newApplicationUrl = "http://" . $domain;
				}
				$config->APPLICATION_URL = $newApplicationUrl;
				$this->smarty->assign ( 'APPLICATION_URL', $newApplicationUrl );
			} else {
				// Goto Home Page of Main Domain				$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/';
				CommonUtils::redirect ( $url );
				return - 1;
			}
		} else {
			//Update APPLICATION_URL configuration		//$newApplicationUrl = $config->APPLICATION_URL . "/" . $username;		//$this->smarty->assign('APPLICATION_URL', $newApplicationUrl);		}
		
		// Get User Exist		$usersDataService = new UsersDataService ();
		$ownerUser = $usersDataService->getByUsername ( $username );
		if (empty ( $ownerUser )) {
			$ownerUser = $usersDataService->getById ( $userId );
			if (empty ( $ownerUser )) {
				// Go on to Page not found				$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/';
				CommonUtils::redirect ( $url );
				return - 1;
			}
		}
		
		// Make sure the $ownerUser is exist		$this->ownerId = $ownerUser->id;
		$this->smarty->assign ( 'ownerId', $this->ownerId );
		
		// Check if this is DEMO User Mode		$tempName = $ownerUser->username;
		if (strcasecmp ( DEMO_USERNAME, $tempName ) == 0) {
			$this->isDemoMode = true;
		}
		$this->ownerFullName = $tempName;
		$this->smarty->assign ( 'ownerFullName', $tempName );
		
		$username = ! empty ( $username ) ? $username . "/" : "";
		$this->ownerName = $username;
		$this->templateName = $ownerUser->getTemplateName ();
		
		if ($this->templateName == "") {
			
			$demoUser = $usersDataService->getByUserName ( DEMO_USERNAME );
			if ($demoUser) {
				
				$this->templateName = $demoUser->getTemplateName ();
			
			} else {
				$this->templateName = "template1";
			}
		}
		
		$this->smarty->assign ( 'ownerName', $username );
		$this->smarty->assign ( 'ownerEmail', $ownerUser->email );
		$this->smarty->assign ( 'templateName', $this->templateName );
		
		//Get Some Information of Current User		$this->loadBasicOwnerInfo ();
		
		// Update Access Rights		$packageOption = $ownerUser->getPackageOption ();
		
		$package_id = - 1;
		if (isset ( $packageOption ))
			$package_id = $packageOption->id;
		
		// Validate Expired		$packageOrderDataService = new PackageOrderDataService ();
		$isExpired = $packageOrderDataService->isExpired ( $this->ownerId, $package_id, $this->isDemoMode );
		if ($isExpired == true) {
			// Go on to login page			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/Index/expired';
			CommonUtils::redirect ( $url );
			return - 1;
		}
		
		if ($packageOption) {
			$this->smarty->assign ( 'isBlogEnabled', $packageOption->isEnabled ( MODULE_BLOGGING ) );
			$this->smarty->assign ( 'isNewsEnabled', $packageOption->isEnabled ( MODULE_NEWS ) );
			$this->smarty->assign ( 'isEcommerceEnabled', $packageOption->isEnabled ( MODULE_ECOMMERCE ) );
			$this->smarty->assign ( 'isGalleryEnabled', $packageOption->isEnabled ( MODULE_GALLERY ) );
			$this->smarty->assign ( 'isBrandingFree', ( bool ) $ownerUser->brandFree );
			$this->currentPackageOption = $packageOption;
		}
		
		// Checking member has been logged in or not		if ($this->authentication->getCurrentUserId () != null) {
			$usersDataService = new UsersDataService ();
			$currentUser = $usersDataService->getById ( $this->authentication->getCurrentUserId () ); //$authentication->getSession();			$this->smarty->assign ( 'hasLoggedIn', true );
			$this->smarty->assign ( 'loggedInName', ! empty ( $currentUser->firstName ) ? $currentUser->firstName : $currentUser->username );
			$this->smarty->assign ( 'loggedInUserType', $currentUser->userType );
			$this->smarty->assign ( 'currentUser', $currentUser );
			$isOwner = ($currentUser->id == $this->ownerId);
			$this->smarty->assign ( 'isWebsiteOwner', $isOwner );
		}
		
		//Get Dynamic Page		$arrElement = array ();
		$arrElement ['ownerId'] = $this->ownerId;
		$arrElement ['type'] = PAGE_CUSTOM;
		$this->userPageDataService = new UserPageDataService ();
		$dynamicPageList = $this->userPageDataService->getItems ( $arrElement );
		$this->smarty->assign ( 'dynamicPageList', $dynamicPageList );
		$this->smarty->assign ( 'isDemoMode', $this->isDemoMode );
		
		$this->userBlogDataService = new UserBlogDataService ();
		$this->userNewsDataService = new UserNewsDataService ();
		$this->userPhotoDataService = new UserPhotoDataService ();
		$this->userProductDataService = new UserProductDataService ();
		
		// Load Latest data		$this->loadLatestData ();
		
		// Check Mobile Mode Browsing		$this->isMobileMode = CommonUtils::detect_mobile ();
	}
	
	/**	 * Set page name	 *	 * @param string $pageName: name of page	 */
	public function setPageName($pageName) {
		$this->smarty->assign ( 'pageName', $pageName );
	}
	
	public function setModuleName($name) {
		$this->smarty->assign ( 'moduleName', $name );
	}
	
	/**	 * Set Meta Title	 */
	public function setPageTitle($title) {
		$this->smarty->assign ( 'headTitle', $title );
	}
	
	/**	 * Set Meta Keywords	 */
	public function setMetaKeywords($keywords) {
		$this->smarty->assign ( 'metaKeywords', $keywords );
	}
	
	/**	 * Set Meta Description	 */
	public function setMetaDescription($description) {
		$this->smarty->assign ( 'metaDescription', $description );
	}
	
	/**	 * Create new action key	 *	 * @return void	 */
	public function createActionKey() {
		// Create new token key		$_SESSION ['tokenKey'] = sha1 ( CommonUtils::randomNumber ( 10 ) );
		
		$this->smarty->assign ( 'actionKey', $_SESSION ['tokenKey'] );
	}
	
	/**	 * Validate Action Key	 *	 * @return bool	 */
	public function validateActionKey() {
		// Get action key		$actionKey = $this->getPost ( 'actionKey', '' );
		
		if (! isset ( $_SESSION ['tokenKey'] ) || $actionKey == $_SESSION ['tokenKey']) {
			// Key has been validated			return true;
		}
		
		return false;
	}
	
	/**	 * Set name of style	 *	 * @param string $styleName: name of style	 */
	public function setStyleName($styleName) {
		$this->smarty->assign ( 'styleName', $styleName );
	}
	
	/**	 * Load basic information of Owner	 */
	private function loadBasicOwnerInfo() {
		$webLogoSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_USER_WEBSITE_LOGO, $this->ownerId );
		$webFaviconSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_USER_WEBSITE_FAVICON, $this->ownerId );
		$facebookSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_USER_FACEBOOk, $this->ownerId );
		$twitterSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_USER_TWITTER, $this->ownerId );
		$linkinSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_USER_LINKIN, $this->ownerId );
		$dribbbleSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_USER_DRIBBBLE, $this->ownerId );
		$diggSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_USER_DIGG, $this->ownerId );
		$vimeoSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_USER_VIMEO, $this->ownerId );
		$youtubeSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_USER_YOUTUBE, $this->ownerId );
		$forrstSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_USER_FORRST, $this->ownerId );
		$flickrSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_USER_FLICKR, $this->ownerId );
		
		$logoUrl = ($webLogoSettingsEntity->value != "") ? Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Resources/Images/' . $webLogoSettingsEntity->value : "";
		$faviconUrl = ($webFaviconSettingsEntity->value != "") ? Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Resources/Images/' . $webFaviconSettingsEntity->value : "";
		$this->smarty->assign ( 'ownerWebLogo', $logoUrl );
		$this->smarty->assign ( 'ownerWebFavicon', $faviconUrl );
		$this->smarty->assign ( 'ownerFacebook', $facebookSettingsEntity->value );
		$this->smarty->assign ( 'ownerTwitter', $twitterSettingsEntity->value );
		$this->smarty->assign ( 'ownerLinkin', $linkinSettingsEntity->value );
		$this->smarty->assign ( 'ownerDribbble', $dribbbleSettingsEntity->value );
		$this->smarty->assign ( 'ownerDigg', $diggSettingsEntity->value );
		$this->smarty->assign ( 'ownerVimeo', $vimeoSettingsEntity->value );
		$this->smarty->assign ( 'ownerYoutube', $youtubeSettingsEntity->value );
		$this->smarty->assign ( 'ownerForrst', $forrstSettingsEntity->value );
		$this->smarty->assign ( 'ownerFlickr', $flickrSettingsEntity->value );
	}
	
	/**	 * Get Application URL	 */
	protected function getApplicationUrl() {
		$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . "/";
		if (! empty ( $this->ownerName )) {
			$url .= $this->ownerName;
		}
		
		return $url;
	}
	
	/**	 * Get User Smarty File Path	 * @param string $content	 */
	protected function assignSmartyContent($content) {
		$templateName = (empty ( $this->templateName )) ? "template1" : $this->templateName;
		
		// Build Layout Path		$layoutPath = APPLICATION_PATH . "/Layouts/" . $templateName . "/MainLayout.tpl";
		
		// Build Smarty Content Path		$smartyContentPath = $this->templateName . "/" . $content;
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', $smartyContentPath );
		$this->smarty->display ( $layoutPath );
	}
	
	/**	 * Check if User Logged	 */
	protected function requireUserLogin() {
		if ($this->authentication->getCurrentUserId () == null) {
			if ($this->ownerId != "") {
				$url = $this->getApplicationUrl () . "Login";
				CommonUtils::redirect ( $url );
				return - 1;
			} else {
				// Redirect to Page Not Found instead				$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/';
				CommonUtils::redirect ( $url );
				return - 1;
			}
		} else if ($this->authentication->getSession ()->userType != ROLE_MEMBER_USER && $this->ownerId != "") {
			// Logout this current user			$url = $this->getApplicationUrl () . "MyAccount/logout";
			CommonUtils::redirect ( $url );
			return - 1;
		}
	}
	
	public function loadLatestData() {
		// Get 5 latest blog entries		$arrElement = array ();
		$arrElement ['status'] = UserBlogEntity::ACTIVE;
		$arrElement ['ownerId'] = $this->ownerId;
		$latestBlogList = $this->userBlogDataService->getItems ( $arrElement, " id DESC", 0, 5 );
		if (count ( $latestBlogList ) > 0) {
			foreach ( $latestBlogList as $item ) {
				$item->body = htmlspecialchars_decode ( $item->body, ENT_QUOTES );
			}
		}
		$this->smarty->assign ( 'latestBlogList', $latestBlogList );
		
		// Get 5 latest gallery		$latestPhotoList = $this->userPhotoDataService->getItems ( $arrElement, " id DESC", 0, 5 );
		
		if (count ( $latestPhotoList ) > 0) {
			foreach ( $latestPhotoList as $item ) {
				$item->description = htmlspecialchars_decode ( $item->description, ENT_QUOTES );
			}
		}
		$this->smarty->assign ( 'latestGalleryList', $latestPhotoList );
		
		// Get 5 latest news		$latestNewsList = $this->userNewsDataService->getItems ( $arrElement, " id DESC", 0, 5 );
		if (count ( $latestNewsList ) > 0) {
			foreach ( $latestNewsList as $item ) {
				$item->body = htmlspecialchars_decode ( $item->body, ENT_QUOTES );
			}
		}
		$this->smarty->assign ( 'latestNewsList', $latestNewsList );
		
		// Get 5 latest Product		$latestProductList = $this->userProductDataService->getItems ( $arrElement, " id DESC", 0, 5 );
		$this->smarty->assign ( 'latestProductList', $latestProductList );
	}
	
	protected function loadAllPayment($userId) {
		// Get Paypay		$paypalUsernameSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_PAYPAL_USERNAME, $userId );
		$paypalPasswordSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_PAYPAL_PASSWORD, $userId );
		$paypalSignatureSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_PAYPAL_SIGNATURE, $userId );
		$paypalTestModeSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_PAYPAL_TESTMODE, $userId );
		$paypalEnableSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_PAYPAL_ENABLE, $userId );
		
		// Get 2Checkout Settings		$checkoutUsernameSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_2CHECKOUT_USERNAME, $userId );
		$checkoutPasswordSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_2CHECKOUT_PASSWORD, $userId );
		$checkoutTestModeSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_2CHECKOUT_TESTMODE, $userId );
		$checkoutEnableSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_2CHECKOUT_ENABLE, $userId );
		
		//google checkout		$googlecheckout_MerchantIdSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_GOOGLECHECKOUT_MERCHANTID, $userId );
		$googlecheckout_MerchantKeySettingsEntity = $this->settingsDataService->getItem ( SETTINGS_GOOGLECHECKOUT_MERCHANTKEY, $userId );
		$googlecheckout_MerchantModeSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_GOOGLECHECKOUT_MODE, $userId );
		$googlecheckout_MerchantEnableSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_GOOGLECHECKOUT_ENABLE, $userId );
		
		//worldpay		$worldpayIdSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_WORLDPAY_INSTALLATIONID, $userId );
		$worldpayPassSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_WORLDPAY_PASSWORD, $userId );
		$worldpaytestModeSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_WORLDPAY_MODE, $userId );
		$worldpayIdEnableSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_WORLDPAY_ENABLE, $userId );
		
		//eway		$ewaycustomerIdSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_EWAY_CUSTOMERID, $userId );
		$ewayusernameSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_EWAY_USERNAME, $userId );
		$ewayreturnurlSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_EWAY_RETURN_URL, $userId );
		$ewaycancelurlSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_EWAY_CANCEL_URL, $userId );
		$ewaytestaccountSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_EWAY_TESTACCOUNT, $userId );
		$ewayenableSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_EWAY_ENABLE, $userId );
		
		// Get Currency		$userCurrencySettingsEntity = $this->settingsDataService->getItem ( SETTINGS_USER_CURRENCY, $userId );
		$this->currencyCode = $userCurrencySettingsEntity->value;
		$this->currencySymbol = $this->settingsDataService->getCurrencySymbol ( $this->currencyCode );
		
		$this->checkout_enable = ( bool ) ($checkoutEnableSettingsEntity->value == "1");
		$this->paypal_enable = ( bool ) ($paypalEnableSettingsEntity->value == "1");
		$this->googlecheckout_enable = ( bool ) ($googlecheckout_MerchantEnableSettingsEntity->value == "1");
		//$this->worldpay_enable = (bool)($worldpayIdEnableSettingsEntity->value == "1");		$this->eway_enable = ( bool ) ($ewayenableSettingsEntity->value == "1");
		
		$this->smarty->assign ( 'paypal_enable', $paypalEnableSettingsEntity->value );
		$this->smarty->assign ( 'checkout_enable', $checkoutEnableSettingsEntity->value );
		$this->smarty->assign ( 'googlecheckout_enable', $googlecheckout_MerchantEnableSettingsEntity->value );
		$this->smarty->assign ( 'worldpay_enable', $worldpayIdEnableSettingsEntity->value );
		$this->smarty->assign ( 'eway_enable', $ewayenableSettingsEntity->value );
		$this->smarty->assign ( 'currencyCode', $this->currencyCode );
		$this->smarty->assign ( 'currencySymbol', $this->currencySymbol );
	}
	
	/**	 * Get User Smarty File Path for Mobile Browsing	 * @param string $content	 */
	protected function assignSmartyMobileContent($content) {
		$templateName = (empty ( $this->templateName )) ? "template1" : $this->templateName;
		
		// Build Layout Path		$layoutPath = APPLICATION_PATH . "/Layouts/" . $templateName . "/MainLayout.tpl";
		
		// Build Smarty Content Path		$smartyContentPath = $this->templateName . "/" . $content;
		$this->smarty->display ( $smartyContentPath );
	}

}